﻿using Dao;
using HospitalErpData.MenuHelper;
using HospitalErpWinUI.GlobalVar;
using Security.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using HospitalErpWinUI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Configuration;

namespace HospitalErpWinUI.MenuPemHelper
{
    public class UserMenuPemHelper
    {
        
        //原始菜单
        public static Dictionary<string, List<Menu_node>> originaLeftMenu { get; set; }
        //分析后菜单
        public static Dictionary<string, List<Menu_node>> leftMenu { get; set; }
        //页面中sqlid权限
        public static Dictionary<string, List<Menu_node>> page { get; set; }

        DaoHelper helper;

        public UserMenuPemHelper()
        {
            helper = new DaoHelper();
            originaLeftMenu = new Dictionary<string, List<Menu_node>>();
            leftMenu = new Dictionary<string, List<Menu_node>>();
            page = new Dictionary<string, List<Menu_node>>();
        }

        private List<Menu_node> GetMenu(string ticket)
        {
            string xml = string.Empty;
            Dictionary<string, string> dic = new Dictionary<string, string>();
            ServiceParamter paramter = new ServiceParamter("menu_"+ G_User.user.Module_name, dic);
            xml = helper.ReadMenuForText(paramter);

            List<Menu_node> nodes = new List<Menu_node>();
            XElement sqls = XElement.Parse(@"" + xml.ToString().Trim() + "");
            Menu_node nod = new Menu_node();
            int id = 0;
            MenuHelp.GetMenusByXml(sqls, ref nodes, ref id, ref nod);
            return nodes;
        }

        //private DataTable  GetPerm(string ticket)
        //{         
        //    Dictionary<string, string> dic = new Dictionary<string, string>();
        //    ServiceParamter paramter = new ServiceParamter("module", dic);
        //    dic.Add("user_code",G_User.user.User_code);
        //    dic.Add("comp_code",G_User.user.Comp_code);
        //    dic.Add("copy_code",G_User.user.Copy_code);
        //    dic.Add("mod_code",G_User.user.Module_name);
        //    DataTable  dt1 = helper.ReadSqlForDataTable(paramter, ticket);

        //    return dt1;
        //}
        private DataTable GetPerm()
        {
         //   string url = @"http://localhost:1278/Services/User/Module";
            string url = ConfigurationManager.AppSettings["ServicesAdress"] + "/User/Module";
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string data = HttpHelper.CreateHttpGetResponse(url, dic, G_User.user.Ticket, "Module");
            JObject jo = (JObject)JsonConvert.DeserializeObject(data);
            DataTable dt = Newtonsoft.Json.JsonConvert.DeserializeObject(jo["Data"].ToString(), typeof(DataTable)) as DataTable;
            return dt;
        }


        public void InitData(UserAuth user)
        {
            //清空
            originaLeftMenu.Clear();
            leftMenu.Clear();
            page.Clear();

            //得到原始菜单
            List<Menu_node> menus = GetMenu(user.Ticket);
            DataTable dt1 = GetPerm();

            #region 移除没有用户权限的节点
                foreach (Menu_node node in menus)
                {
                    if (node.page != null)
                    {
                        for (int i = 0; i < node.page.perms.Count; i++)
                        {
                            if (!IsHasPerm(node.page.perms[i].name, dt1))
                            {
                                node.page.perms[i].isSelected = true;
                            }
                        }

                        node.page.perms.RemoveAll(w => w.isSelected == true);
                        if (node.page.perms.Count == 0)
                        {
                            menus.Find(w => w.oid == node.oid).isSelected = true;

                        }

                    }
                }
                menus.RemoveAll(w => w.isSelected == true);
            #endregion           

            RemoveNotPermNodes(ref menus);

            originaLeftMenu.Add("originaLeftMenu", menus);

            //得到右边菜单
            List<Menu_node> tempMenu = new List<Menu_node>();
            foreach (Menu_node node in originaLeftMenu["originaLeftMenu"])
            {
                if (node.tab != null)
                {
                    tempMenu.Add(node);

                }
                if (node.page == null)
                    continue;
                if (!string.IsNullOrEmpty(node.page.src))
                {
                    Menu_node menu_node = originaLeftMenu["originaLeftMenu"].Where(w => w.oid == node.parentId && w.tab == true).FirstOrDefault<Menu_node>();
                    if (menu_node != null)
                    {
                        continue;
                    }
                    if (!tempMenu.Contains(node))
                    {
                        tempMenu.Add(node);
                    }
                }
            }

            List<Menu_node> tempMenu1 = originaLeftMenu["originaLeftMenu"];

            foreach (Menu_node nod in tempMenu)
            {
                //给page 赋值
                List<Menu_node> query = tempMenu1.Where(w => w.parentId == nod.oid).ToList();
                if (query.Count > 0)
                {
                    page.Add(nod.key.ToString(), query);
                }
                else
                {
                    List<Menu_node> query1 = tempMenu1.Where(w => w.oid == nod.oid).ToList();
                    page.Add(nod.key.ToString(), query1);
                }
               

                tempMenu1.RemoveAll(w => w.parentId == nod.oid);
            }
            leftMenu.Add("leftMenu", tempMenu1);
            //得到页面对应的sqlId
        }

        private bool IsHasPerm(string perm_id ,DataTable dt)
        {
            bool result = false;
            foreach(DataRow dr in dt.Rows)
            {
                if (dr[0].ToString().Equals(perm_id))
                {
                    result = true;
                    break;
                }
            }
            return result;
        
        }

        //递归删除用户没有权限的节点
        private static void RemoveNotPermNodes( ref List<Menu_node> menus )
        { 
            foreach(Menu_node node in menus)
            {
                var query = menus.FindAll(w => w.parentId == node.oid ).ToList<Menu_node>();
                //没有子节点 并且page 为空
                if (query.Count ==0  && node.page == null)
                {
                    menus.Find(w=>w.oid == node.oid).isSelected= true;
                }
            }

            var deleteNodes = menus.FindAll(w => w.isSelected == true).ToList<Menu_node>();
            if (deleteNodes.Count > 0)
            {
                menus.RemoveAll(w => w.isSelected == true);
                RemoveNotPermNodes(ref menus);
            }
            else
            {
                return;
            }
        }
    }
}
